package com.example.demo.Controller;

import com.example.demo.dto.ApiResponse;
import com.example.demo.dto.LoginRequest;
import com.example.demo.dto.LoginResponseDto;
import com.example.demo.dto.UserResponseDto;
import com.example.demo.dto.UserUpdateRequestDto; // 新增导入
import com.example.demo.entity.User;
import com.example.demo.security.JwtUtil;
import com.example.demo.service.impl.UserDetailsServiceImpl;
import com.example.demo.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
// import org.springframework.security.core.context.SecurityContextHolder; // 用于权限校验示例
// import org.springframework.security.core.authority.SimpleGrantedAuthority; // 用于权限校验示例
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserDetailsServiceImpl userDetailsServiceImpl;

    @PostMapping("/register")
    public ResponseEntity<ApiResponse<UserResponseDto>> registerUser(@Valid @RequestBody User userToRegister) {
        try {
            User newUser = userService.register(userToRegister);
            UserResponseDto userResponseDto = UserResponseDto.fromUser(newUser);
            return ResponseEntity.status(HttpStatus.OK)
                    .body(ApiResponse.created("注册成功", userResponseDto));
        } catch (RuntimeException e) {
            if (e.getMessage() != null && e.getMessage().startsWith("账号已存在")) {
                return ResponseEntity.status(HttpStatus.CONFLICT)
                        .body(ApiResponse.conflict(e.getMessage()));
            } else if (e.getMessage() != null && (e.getMessage().contains("不能为空") || e.getMessage().contains("长度不能少于"))) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(ApiResponse.badRequest(e.getMessage()));
            }
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.internalServerError("注册失败：" + e.getMessage()));
        }
    }

    @PostMapping("/login")
    public ResponseEntity<ApiResponse<LoginResponseDto>> loginUser(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginRequest.getAccount(), loginRequest.getPassword())
            );
            final UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(loginRequest.getAccount());
            final String jwt = jwtUtil.generateToken(userDetails);
            User userEntity = userService.getUserByAccount(loginRequest.getAccount());
            UserResponseDto userResponseDto = UserResponseDto.fromUser(userEntity);
            LoginResponseDto loginResponseDto = new LoginResponseDto(jwt, userResponseDto);
            return ResponseEntity.ok(ApiResponse.ok("登录成功", loginResponseDto));
        } catch (BadCredentialsException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.unauthorized("用户名或密码错误"));
        } catch (RuntimeException e) {
            if (e.getMessage() != null && e.getMessage().contains("用户未找到")) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(ApiResponse.unauthorized("用户名或密码错误"));
            }
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.internalServerError("登录时发生内部错误：" + e.getMessage()));
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<UserResponseDto>> getUserById(@PathVariable Integer id) {
        try {
            User user = userService.getUserById(id);
            UserResponseDto userResponseDto = UserResponseDto.fromUser(user);
            return ResponseEntity.ok(ApiResponse.ok(userResponseDto));
        } catch (RuntimeException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.notFound(e.getMessage()));
        }
    }

    @GetMapping("/account/{account}")
    public ResponseEntity<ApiResponse<UserResponseDto>> getUserByAccount(@PathVariable String account) {
        try {
            User user = userService.getUserByAccount(account);
            UserResponseDto userResponseDto = UserResponseDto.fromUser(user);
            return ResponseEntity.ok(ApiResponse.ok(userResponseDto));
        } catch (RuntimeException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.notFound(e.getMessage()));
        }
    }

    @GetMapping
    public ResponseEntity<ApiResponse<List<UserResponseDto>>> getAllUsers() {
        try {
            List<User> users = userService.getAllUsers();
            List<UserResponseDto> userResponseDtos = users.stream()
                    .map(UserResponseDto::fromUser)
                    .collect(Collectors.toList());
            return ResponseEntity.ok(ApiResponse.ok(userResponseDtos));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.internalServerError("获取用户列表失败: " + e.getMessage()));
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<UserResponseDto>> updateUser(
            @PathVariable Integer id,
            @Valid @RequestBody UserUpdateRequestDto userUpdateRequestDto) {

        try {
            User updatedUser = userService.updateUser(id, userUpdateRequestDto);
            UserResponseDto userResponseDto = UserResponseDto.fromUser(updatedUser);
            return ResponseEntity.ok(ApiResponse.ok("用户信息更新成功", userResponseDto));
        } catch (RuntimeException e) {
            if (e.getMessage() != null && e.getMessage().contains("用户未找到")) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(ApiResponse.notFound(e.getMessage()));
            } else if (e.getMessage() != null && (
                    e.getMessage().contains("不能为空") ||
                            e.getMessage().contains("长度不能超过") ||
                            e.getMessage().contains("已被其他用户使用") ||
                            e.getMessage().contains("不能为负数"))) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(ApiResponse.badRequest(e.getMessage()));
            }
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.internalServerError("更新用户信息失败: " + e.getMessage()));
        }
    }

    @PostMapping("/{id}/change-password")
    public ResponseEntity<ApiResponse<Void>> changePassword(
            @PathVariable Integer id,
            @RequestBody Map<String, String> passwordChangeRequest) {
        String oldPassword = passwordChangeRequest.get("oldPassword");
        String newPassword = passwordChangeRequest.get("newPassword");

        try {
            userService.changePassword(id, oldPassword, newPassword);
            return ResponseEntity.ok(ApiResponse.okMessage("密码修改成功"));
        } catch (RuntimeException e) {
            if (e.getMessage() != null && e.getMessage().contains("用户未找到")) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(ApiResponse.notFound(e.getMessage()));
            }
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.badRequest(e.getMessage()));
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteUser(@PathVariable Integer id) {
        try {
            userService.deleteUser(id);
            return ResponseEntity.ok(ApiResponse.okMessage("用户删除成功"));
        } catch (RuntimeException e) {
            if (e.getMessage() != null && e.getMessage().contains("用户未找到")) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(ApiResponse.notFound(e.getMessage()));
            }
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.badRequest("删除用户失败: " + e.getMessage()));
        }
    }
}
